package com.hanson.global;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanson.common.api.CommonResult;
import com.hanson.common.api.PageResult;
import com.hanson.common.exception.DmallException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @description: 全局处理响应数据
 * @classname: ResponseControllerAdvice
 * @author: Hanson
 * @create: 2021/01/08
 **/

@RestControllerAdvice(basePackages = {"com.hanson.controller"}) // 这里要加上需要扫描的包
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClazz) {
        // 如果接口返回的类型本身就是CommonResult或者PageResult那就没有必要进行额外的操作，返回false
        return !(returnType.getParameterType().equals(CommonResult.class) | returnType.getParameterType().equals(PageResult.class));
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        // String类型不能直接包装，所以要进行些特别的处理
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultVO里后，再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(new CommonResult<>(data));
            } catch (JsonProcessingException e) {
                throw new DmallException("接口字符串数据包装返回结果异常");
            }
        }
        // 将原本的数据包装在CommonResult里
        return new CommonResult<>(data);
    }
}
